# Load necessary libraries

# Prepare dataset
# Trait data (columns 2:9)
trait.data <- new.d

# Damage data (columns 2:3)
damage_subset <- mean_damage_df.1

# Ensure response column is explicitly named
colnames(damage_subset)[1] <- "tip.label"  # Rename first column to 'response'
colnames(damage_subset)[4] <- "response"  # Rename first column to 'response'

# # Combine trait data and damage data into one dataset
# data <- cbind(damage_subset, trait.data)  # Ensure alignment of rows

# If there's an ID column, use merge instead:
data <- merge(damage_subset, trait.data, by = "tip.label")
data$tip.label <- as.factor(data$tip.label)

# Remove rows with NA values in either the response or predictors
data <- data %>% na.omit()
trait.data <- data[,c(14:21)]
# Generate all combinations of 1,2, and 3 traits
trait_combinations <- lapply(1:3, function(n) {
  combn(colnames(trait.data), n, simplify = FALSE)
}) %>%
  unlist(recursive = FALSE)  # Flatten the list of combinations

# Fit GLMs and store formulas and AIC values
results <- lapply(trait_combinations, function(predictor_set) {
  # Construct formula
  formula <- as.formula(paste("response ~", paste(predictor_set, collapse = " + ")))
  
  # Try fitting the model, handle errors gracefully
  tryCatch({
    model <- glm(formula, data = data,family = gaussian)  # Adjust family if necessary
    list(formula = formula, aic = AIC(model))  # Return formula and AIC
  }, error = function(e) {
    list(formula = formula, aic = NA)  # Return NA for failed models
  })
})

# Remove models with NA AICs
results <- results[!sapply(results, function(x) is.na(x$aic))]

# Extract AIC values and formulas into a data frame
results_df <- do.call(rbind, lapply(results, function(res) {
  data.frame(formula = deparse(res$formula), aic = res$aic)
}))

# Sort by AIC
results_df <- results_df %>% arrange(aic)

# Print the best model
cat("Best Model:\n")
print(results_df[1, ])

# Optional: Show all models sorted by AIC
cat("\nAll Models Sorted by AIC:\n")
print(results_df)

# Calculate ΔAIC
delta_aic <- results_df$aic - min(results_df$aic)
delta_aic

# Calculate Akaike weights
akaike_weights <- exp(-0.5 * delta_aic) / sum(exp(-0.5 * delta_aic))
akaike_weights

# Summary table
aic_table <- data.frame(
  Model = results_df$formula,
  AIC = results_df$aic,
  Delta_AIC = delta_aic,
  Akaike_Weight = akaike_weights
)

# Sort by AIC
aic_table <- aic_table[order(aic_table$AIC), ]
print(aic_table)


# Plot observed vs. predicted
# Best fit model:
model5 <- glm(response ~ lma + height + PPE, data = data,family=gaussian)
vif(model5)
# McFadden's R²: Measures the improvement of the model 
# compared to a baseline (null) model. 
# It ranges from 0 to 1, where higher values indicate
# better fit.
# Calculate McFadden's R^2
1 - (model5$deviance / model5$null.deviance)

summary(model5)

# Plot the effect of lma
lma_range <- seq(min(data$lma), max(data$lma), length.out = 100)
lma_data <- data.frame(lma = lma_range, height = mean(data$height),PPE = mean(data$PPE))
lma_data$response <- predict(model5, newdata = lma_data, type = "response")

ggplot(lma_data, aes(x = lma, y = response)) +
  geom_line(color = "blue") +
  labs(x = "lma", y = "Predicted Response", title = "Effect of lma on Response") +
  theme_minimal()

# Plot the effect of height
height_range <- seq(min(data$height), max(data$height), length.out = 100)
height_data <- data.frame(height = height_range, lma = mean(data$lma), PPE = mean(data$PPE))
height_data$response <- predict(model5, newdata = height_data, type = "response")

ggplot(height_data, aes(x = height, y = response)) +
  geom_line(color = "red") +
  labs(x = "height", y = "Predicted Response", title = "Effect of height on Response") +
  theme_minimal()

# Plot the effect of PPE
ppe_range <- seq(min(data$PPE), max(data$PPE), length.out = 100)
ppe_data <- data.frame(PPE = ppe_range, lma = mean(data$lma), height = mean(data$height))
ppe_data$response <- predict(model5, newdata = ppe_data, type = "response")

ggplot(ppe_data, aes(x = PPE, y = response)) +
  geom_line(color = "purple") +
  labs(x = "PPE", y = "Predicted Response", title = "Effect of PPE on Response") +
  theme_minimal()

